<template>
	<view class="content">
		<ad adpid="1206517737" type="banner"></ad>
		<ad-common-rewarded ref="rewardedRef" @adEnd="onAdEnd" @adExit="onadExit" @adError="onAdError">
		</ad-common-rewarded>
		<ad-interstitial adpid="1076934123" :loadnext="true" ref="adInatance">
		</ad-interstitial>
		<!-- 插屏广告 -->
		<!-- <ad-common-interstitial ref="adInatance"></ad-common-interstitial> -->
		<!-- 我可连接的wifi -->
		<view class="item item2">
			<view class="left">
				<cloud-image v-if="hasLogin&&userInfo.data.avatar_file" :src="userInfo.data.avatar_file.url"
					width="120rpx" height="100%">
				</cloud-image>
				<uni-icons v-else custom-prefix="iconfont" type="icon-anonymous" size="60"></uni-icons>
			</view>
			<view class="left1">
				<view v-if="hasLogin">
					{{ userInfo.data.nickname}}
				</view>
				<view class="bottom">
					点击下方按钮安全连接 WiFi
				</view>
			</view>
			<view class="right">
				<uni-icons type="arrow-right" size="28" color="#999999"></uni-icons>
			</view>
		</view>
		<view class="item item2">
			<view class="left">
				<image src="/static/WIFI.png" mode="widthFix"
					style="width:120rpx;height: 100%;background-color: #fe4066"></image>
			</view>
			<view class="left1">
				<view>
					{{wifiData.data && wifiData.data.wifi_name}}
				</view>
				<view class="bottom">
					安全连接
				</view>
			</view>
			<view class="right">
				<uni-icons type="arrow-right" size="28" color="#999999"></uni-icons>
			</view>
		</view>
		<uni-notice-bar text="连接 WiFi 功能需要打开 WiFi 开关,请提前打开。如果失败可前往设置页面直接连接。" />
		<!-- 如果自动连接的话那么就把这个放开 -->
		<!-- <view v-if="connectFail"> -->
		<!-- 连接成功后把按钮隐藏 -->
		<view>
			<!-- <button @click="getUserInfo(true)" type="primary">连接wifi</button> -->
			<button @click="clickConnectBtn()" type="primary" :disabled="connectedSuccess">连接wifi</button>
		</view>
	</view>
</template>

<script>
	import {
		onLoad
	} from '@dcloudio/uni-app';
	const db = uniCloud.database();
	const usersTable = db.collection('uni-id-users')
	// const userRoleTable = db.collection('uni-id-roles')
	const uniIdCo = uniCloud.importObject("uni-id-co")
	const wifiTable = db.collection('wifi')
	const wifiConnectTable = db.collection('wifi_connect_records')
	// 引入激励视频广告
	// import {rewarded} from "@/common/ad.js"

	import {
		ref,
		reactive
	} from 'vue';
	import errorCode from "@/common/errorCode.js"
	const {
		wifiErrorCode
	} = errorCode
	export default {
		setup() {
			const connectedSuccess = ref(false)
			const connectFail = ref(false)
			// const userProfileRef = ref();
			const hasLogin = ref(false);
			const hasUserNotNickName = ref(false);
			const userInfo = reactive({
				data: {}
			})
			// 存放连接过来的wifiid
			const wifiId = ref("")
			const wifiData = reactive({
				data: {}
			})
			const rewardedRef = ref(null)
			// 插屏广告组件
			const adInatance = ref(null)
			
			const toMngWifi = () => {
				uni.navigateTo({
					url: "/pages/index/index"
				})

			}
			onLoad(async (option) => {
				// console.log("扫码后进入页面的页面参数", option)
				if (option.wifi_id) {
					wifiId.value = option.wifi_id
				}
				// uni.showLoading({
				// 	mask: true
				// });
				getUserInfo(true)

				uni.$on('reloadIndex', () => {
					getUserInfo(true)
				});
				setTimeout(() => {
					adInatance.value.show()
				}, 1000)
				// loginByWeixin()
			})
			const loginByWeixin = async () => {
				// console.log("login")
				// uni.navigateTo({
				// 	url: "pages/login/pages/login/login-withoutpwd?type=weixin"
				// })
				uni.showLoading({
					mask: true,
					title: '用户登录中'
				});
				let res = await new Promise((callBack) => {
					uni.getUserProfile({
						desc: "用于设置账户昵称和头像",
						complete: (e) => {
							// console.log("getUserProfile:", e);
							callBack(e)
						}
					})
				})
				// console.log("getUserProfile:", res);
				if (res.errMsg != "getUserProfile:ok") {
					uni.showToast({
						title: '用户取消授权',
						icon: 'none'
					});
					uni.hideLoading()
					return
				}
				
				
				const type = "weixin"
				// 先只支持微信登录
				uni.login({
					"provider": type,
					"onlyAuthorize": true,
					success: async e => {
						// console.log("e微信登录完成", e);
						login({
							code: e.code
						}, type,res)
					},
					fail: async (err) => {
						// console.log("微信登录err", err);
						uni.hideLoading()
					}
				})
			}
			const login = (params, type,userInfoRes) => { //联网验证登录
				// console.log({
				// 	params,
				// 	type
				// });
				//toLowerCase
				let action = 'loginBy' + type.trim().toLowerCase().replace(type[0], type[0].toUpperCase())
				const uniIdCo = uniCloud.importObject("uni-id-co", {
					customUI: true
				})
				uniIdCo[action](params).then(result => {
						// console.log("调用云对象登录login-result", result);

						// #ifdef MP-WEIXIN
						//如果是微信小程序端的微信登录，且为首次登录，就弹出获取微信昵称+头像用于绑定资料
						if (type == 'weixin' && result.type == "register") {
							// loginSuccess({
							// 	...result,
							// 	showToast: false,
							// 	autoBack: false
							// })
							// return
							// userProfileRef.value.open(result.uid, wifiId)
							updateUserInfo(result.uid, userInfoRes)
						} else {
							uni.showToast({
								title: '登录成功',
								icon: 'none'
							});
							if (hasUserNotNickName.value) {
								// 已经有用户信息但是没昵称和头像
								updateUserInfo(result.uid, userInfoRes)
							} else {
								// 啥都有了直接获取信息就可以
								getUserInfo()
							}
							// userProfileRef.value.closeMe()
						}
						// #endif
						// loginSuccess(result)
					})
					.catch(e => {
						// console.log(e);
						uni.showModal({
							content: e.message,
							confirmText: "知道了",
							showCancel: false
						});
					})
					.finally(e => {
						uni.hideLoading()
					})
			}
			
			const updateUserInfo = async (userId, userInfoRes) => {
				let res = userInfoRes
				// uni.showLoading();
				// let res = await new Promise((callBack) => {
				// 	uni.getUserProfile({
				// 		desc: "用于设置账户昵称和头像",
				// 		complete: (e) => {
				// 			console.log("getUserProfile:", e);
				// 			callBack(e)
				// 		}
				// 	})
				// })
				// // console.log("userInfo", res.userInfo);
				// if(res.errMsg != "getUserProfile:ok"){
				// 	uni.showToast({
				// 		title: '用户取消授权',
				// 		icon: 'none'
				// 	});
				// 	return
				// }
				// console.log("注册用户信息")
				let {
					avatarUrl,
					nickName
				} = res.userInfo, cloudPath = userId + '/' + Date.now() + 'avatarUrl.jpg';
				// console.log("注册用户信息-nickName",nickName)
				// console.log("注册用户信息-avatarUrl",avatarUrl)
				let tempFilePath = await new Promise((callBack) => {
					uni.downloadFile({
						url: avatarUrl,
						success: (res) => {
							if (res.statusCode === 200) {
								// console.log('下载成功');
								callBack(res.tempFilePath)
							}
							callBack()
						},
						fail: (err) => {
							console.error(err)
						},
						complete: (e) => {
							// console.log("downloadFile",e);
						}
					});
				})
				// console.log(tempFilePath);
				const result = await uniCloud.uploadFile({
					filePath: tempFilePath,
					cloudPath,
					fileType: 'image'
				});
				// console.log("上传成功",{result});
				let userInfo = {
					"nickname": nickName,
					"avatar_file": {
						name: cloudPath,
						extname: "jpg",
						url: result.fileID
					},
					// 如果那个人是连接wifi的则赋予消费者角色
					"role": ["consumer"]
				}
				doUpdate(userInfo)
			}
			
			const doUpdate = (data) => {
				// console.log('dododo',data);
				// 使用 clientDB 提交数据
				usersTable.where('_id==$env.uid').update(data).then((res) => {
					uni.showToast({
						title: '登录成功',
						icon: 'none'
					});
					// console.log("注册完成后更新nicknaem和role成功")
					getUserInfo()
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			}
			// 1.获取用户信息
			const getUserInfo = (flag) => {
				// uni.showLoading({
				// 	mask: true,
				// 	title: '正在查询用户信息'
				// });
				uni.showLoading({
					mask: true
				});
				const user = usersTable.where("'_id' == $cloudEnv_uid").get();
				// console.log(user)
				user.then(res => {
					// console.log("getUserInfo", {
					// 	res
					// });
					const userData = res.result.data[0]
					// console.log("userData",userData)
					if(userData){
						if (userData.nickname) {
							// 有用户信息
							userInfo.data = userData
							// console.log('this.userInfo', userInfo.data);
							hasLogin.value = true
							uni.setStorageSync("userInfo", userData)
							// 如果wifi_id不为空则找到对应的wifi数据，并且连接wifi
							getWifiByWifiId()
							// 加载激励视频广告
							// rewarded.load()
						} else {
							// 没用用户信息，则先登录
							// if (flag) {
							// 	loginByWeixin()
							// }
							// console.log("就说明有用户信息，但是用户没头像和昵称,这时候可以获取头像和昵称然后更新一下")
							hasLogin.value = false
							hasUserNotNickName.value = true
							// if (flag) {
							// 	loginByWeixin()
							// }
						}
					}else{
						hasLogin.value = false
						// if (flag) {
						// 	loginByWeixin()
						// }
					}
					


					// store.commit("login",true)
					// store.commit("setUserInfo",res.result.data[0])
				}).catch(e => {
					userInfo.data = {}
					uni.setStorageSync("userInfo", null)
					hasLogin.value = false
					// store.commit("logout")
					// console.log("报错了", e.message, e.errCode);
					// if (flag) {
					// 	loginByWeixin()
					// }

				}).finally(e => {
					// console.log(e);
					uni.hideLoading()
				})
			}
			// 通过wifiId获取wifi信息
			const getWifiByWifiId = async () => {
				// console.log("getWifiByWifiId")
				uni.showLoading({
					mask: true,
					title: '正在获取wifi信息中'
				});
				const res = await wifiTable.where({
					_id: wifiId.value
				}).get({
					getOne: true
				})
				// console.log("wifi-result",res)
				const result = res.result.data
				wifiData.data = result
				// const {
				// 	wifi_name,
				// 	provider_name,
				// 	password,
				// 	qrcode_file,
				// 	_id
				// } = result
				// 找到wifi数据后将wifi_id写入userde wifi字段
				updateUserWifi()
			}
			const updateUserWifi = async () => {
				// const {result} = await usersTable.where("'_id'==$cloudEnv_uid").get()
				// const wifi = result.data[0].wifi || []
				// wifi.push(wifiId)
				// console.log("wifi",wifi)
				const result = uni.getStorageSync("userInfo")
				const wifi = result.wifi || []
				// 解决bug：用户重复连接某个wifi时候，wifiId字段会出现重复
				if (!wifi.includes(wifiId.value)) {
					wifi.push(wifiId.value)
					const res = await usersTable.where('_id==$cloudEnv_uid').update({
						wifi
					})
					// console.log("更新用户的wifi完成", res)
					// 取消自动连接-让点击按钮连接
					// content_wf()
				} else {
					// content_wf()
				}

			}
			// 点击连接wifi按钮
			const clickConnectBtn = () => {
				if (hasLogin.value) {
					uni.showModal({
						title: '连接wifi',
						content: '观看一段小视频后可获得连接wifi的奖励，是否观看？',
						success: function(res) {
							if (res.confirm) {
								// console.log('用户点击确定');
								rewardedRef.value.show()
							} else if (res.cancel) {
								uni.showToast({
									title: '抱歉，您放弃了',
									duration: 2000
								});
							}
						}
					});
				} else {
					// getUserInfo(true)
					loginByWeixin()
				}
				
			}
			// 用户看完广告正确退出视频
			const onAdEnd = () => {
				// console.log("用户看完视频连接wifi")
				// 用户看完广告视频现在可以直接连接
				content_wf()
				// rewarded.show("1851307261",()=>{
				// 	content_wf()
				// })
			}

			// 用户中途取消了观看视频
			const onadExit = () => {
				// 这里提示用户取消了观看，咨询是否需要重新打开
				uni.showModal({
					title: '连接wifi',
					content: '您因中途退出未获取资格，是否重新观看？',
					success: function(res) {
						if (res.confirm) {
							// console.log('用户点击确定');
							rewardedRef.value.show()
						} else if (res.cancel) {
							uni.showToast({
								title: '抱歉，您放弃了',
								duration: 2000
							});
						}
					}
				});
			}

			const onAdError = () => {
				uni.showToast({
					title: '抱歉，视频播放错误',
					duration: 2000,
					success() {
						// 重新显示
						rewardedRef.value.load().then(() => rewardedRef.value.show())
							.catch(err => {
								// console.log('激励视频 广告显示失败')
							})
					}
				});
			}
			const content_wf = () => {
				// console.log("点击连接wifi")
				uni.getSystemInfo({
					success: (res) => {
						// console.log("获取系统信息成功")
						let system = ''
						// console.log("当前手机型号===>",res)
						if (res.platform == 'android') {
							system = parseInt(res.platform.substr(8))
						}
						if (res.platform == 'ios') {
							system = parseInt(res.platform.substr(4))
						}
						if (res.platform == 'android' && system < 6) {
							uni.showToast({
								title: '手机版本不支持',
								icon: 'none'
							})
							return
						}
						if (res.platform == 'ios' && system < 11.2) {
							uni.showToast({
								title: '手机版本不支持',
								icon: 'none'
							})
							return
						}
						//初始wifi模块
						start_wifi()
					}
				})
			}
			const start_wifi = () => {
				uni.showLoading({
					mask: true,
					title: '正在启动wifi'
				});
				uni.startWifi({
					success: (res) => {
						// console.log("startWifi==>", res)
						uni.showToast({
							title: '初始化成功',
							icon: 'error'
						})
						connected()
					},
					fail: (error) => {
						// console.log("初始化失败", error)
						let errorMsg = "初始化失败"
						if (error.errCode && wifiErrorCode[error.errCode]) {

							errorMsg = wifiErrorCode[error.errCode]
						}
						uni.showModal({
							title: '提示',
							content: errorMsg || '连接失败',
							success: function(res) {
								if (res.confirm) {
									// console.log('用户点击确定');
								} else if (res.cancel) {
									// console.log('用户点击取消');
								}
							}
						});
						setConnectData("fail")
						connectFail.value = true
					}
				})
			}
			// 连接wifi
			const connected = () => {
				// console.log("正式连接wifi")
				uni.showToast({
					title: '连接中',
					icon: 'error'
				})
				uni.connectWifi({
					partialInfo: true,
					SSID: wifiData.data.wifi_name, //Wi-Fi 设备名称
					password: wifiData.data.password, //Wi-Fi 密码
					// SSID: "webfz", //Wi-Fi 设备名称
					// password: "fwc18717394609", //Wi-Fi 密码
					success(res) {
						// console.log("连接成功", res)

						uni.showModal({
							title: '提示',
							content: '连接成功',
							success: function(res) {
								if (res.confirm) {
									// console.log('用户点击确定');
								} else if (res.cancel) {
									// console.log('用户点击取消');
								}
							}
						});
						connectFail.value = false
						connectedSuccess.value = true

						// 连接成功后更新wifi连接成功次数
						setConnectData("success")
						// wifiTable.where({
						// 	_id: wifiId.value
						// }).update({
						// 	connect_count: ++wifiData.data.connect_count
						// })
					},
					fail(error) {
						setConnectData("fail")
						// console.log("连接失败", error)
						uni.showModal({
							title: '提示',
							content: '连接失败',
							success: function(res) {
								if (res.confirm) {
									// console.log('用户点击确定');
								} else if (res.cancel) {
									// console.log('用户点击取消');
								}
							}
						});
						connectFail.value = true
					}
				})
			}
			const setConnectData = (type) => {
				const recordData = {
					connect_user: userInfo.data._id,
					wifi_id: wifiId.value,
					connect_time: Date.now(),
					connect_type: type
				}
				wifiConnectTable.add(recordData)
			}
			return {
				getUserInfo,
				hasLogin,
				// userProfileRef,
				userInfo,
				toMngWifi,
				content_wf,
				wifiData,
				connectFail,
				rewardedRef,
				clickConnectBtn,
				onAdEnd,
				onadExit,
				onAdError,
				connectedSuccess,
				adInatance
			}
		}
	}
</script>

<style lang="scss">
	$itemWidth: 60px;

	.item {
		height: $itemWidth;
		padding: 16px 8px;
		background-color: #ffffff;
		margin: 32rpx 16rpx;
		border-radius: 10rpx;
	}

	.item2 {
		display: flex;
		flex-direction: row;
		align-items: flex-start;
		justify-content: space-between;

		.left {
			height: 100%;
		}

		.left1 {
			flex: 1;
			margin-left: 32rpx;
			font-size: 46rpx;

			.bottom {
				color: #999;
				font-size: 32rpx;
				margin-top: 5px;
			}
		}

		.right {
			line-height: $itemWidth;

		}
	}
</style>
